package Page.LoginInterfacePage;

import Controller.LoginAndExitException.WrongPassWordOrIdException;
import Controller.MainController;
import Navigation.NavigationController;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.control.Alert;

/**
 * @since 2024-06-06
 */
public class LoginInterfaceViewModel {

    private final StringProperty userId = new SimpleStringProperty();

    private final StringProperty password = new SimpleStringProperty();

    public void updateUser(String userId) {
        this.userId.set(userId);
    }
    public void updatePassword(String password) {
        this.password.set(password);
    }

    public StringProperty getUserIdProperty() {
        return this.userId;
    }
    public StringProperty getPasswordProperty() {
        return this.password;
    }

    public void backButtonClicked(){
        NavigationController.back();
    }

    // 标志是否尝试管理员登录
    private BooleanProperty ifManager = new SimpleBooleanProperty(false);
    // 按键提示
    private StringProperty ButtonText = new SimpleStringProperty("管理员");


    public StringProperty getButtonText() {
        return ButtonText;
    }

    public BooleanProperty ifManagerProperty() {
        return ifManager;
    }

    /**
     * 尝试登录
     */
    public void loginButtonClicked(){
        System.out.println("Login Button clicked in viewModel");
        String account = this.userId.getValue();
        String password = this.password.getValue();
        System.out.println(account+" "+password);
        if(!this.ifManager.get())
        {
            // 尝试登录
            try{
                MainController.login(account, password);
            }catch(WrongPassWordOrIdException e){
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("登录失败");
                alert.setHeaderText(null);
                alert.setContentText("请检查账户和密码");
                alert.showAndWait();
            }
        }else{
            try{
                MainController.managerLogin(password);
            }catch (WrongPassWordOrIdException e)
            {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("登录失败");
                alert.setHeaderText(null);
                alert.setContentText("请检查账户和密码");
                alert.showAndWait();
            }
        }
    }

    /**
     * 切换登录状态
     */
    public void managerLoginButtonCLicked(){
        this.ifManager.set(true);
        if(this.ifManager.get())
        {
            this.ButtonText.set("普通用户");
        }else{
            this.ButtonText.set("管理员");
        }
    }
}
